(function(){

	if (!window.CJ) {
		window.CJ = {};
	}
	if (!window.CJ.plugin) {
		window.CJ.plugin = {};
	}
	var _APP_ID = "cj_eandm";
	var _BILLING_SINGLE_ = "PPV_CJENMPOC_{{programID}}+{{episodenumber}}";
	var _BILLING_SERIES = "PPS_CJENMPOC_{{programID}}";
	var _BILLING_MONTH  = "PPM_CJENMPOC";
	var _BILLING_CHECK_TYPE = 'cp';// lg 빌링 Plugin 확인 , cp 빌링서버에 확인
	var _SELLERFLAG = 2;
	var _CHARGEPRDUNIT = 2; //자동결재를 위한 단위 (2: 월)
	var _CHARGEPRDVAL = 1;
	var _CURRCODE = "KRW";
	var _CNTRYCODE = 'KR';
	var _PURCOUNT = 1;
	var _REQENCDATA = "null";
	var _STRAPPID ='cj_eandm';


	var _PRODUCT_NAME = {
		'single' : '에피소드 단건 구매',
		'series' : '시리즈 구매',
		'term' : '월정액'
	};

	CJ.plugin.billing = {
		init : function () {
			this.DeviceAPI = document.getElementById('service');
		},
		getAppID : function () {
			try{
				var result_object = this.DeviceAPI.getAppID();
				return result_object.AppID;
			} catch  (err) {
				console.log(err.message);
				if (!CJ.IS_TV) {
					return _APP_ID;
				}
			}
		},
		getUserID : function () {
			try{
				var result_object = service.getUserID();
				return result_object.userID;
			} catch  (err) {
				console.log(err.message);
				if (!CJ.IS_TV) {
					return "dev@cj.com";
				}
			}
		},
		getDeviceID : function () {
			try{
				var result_object = this.DeviceAPI.getDeviceID();
				return result_object.deviceID;
			} catch  (err) {
				console.log(err.message);
				if (!CJ.IS_TV) {
					return "af20c3961a";
				}
			}
		},
		getProductIDs : function (pid, eid) {
			return _BILLING_SINGLE_.replace('{{programID}}', pid).replace('episodenumber', eid) + ','
					+ _BILLING_SERIES.replace('{{programID}}', pid) + ','
					+ _BILLING_MONTH;
		},
		getBillingUrl: function() {
			//var port = window.location.port;
			var billingUrl = "kr.lgappstv.com";
			//테스트 빌링
			billingUrl = "qt-kr.lgappstv.com";

			if(typeof this.DeviceAPI.getBillingUrl == "function"){
				billingUrl = this.DeviceAPI.getBillingUrl();
			}// else {
				// if (port == "8002") {
					// billingUrl = "qt-kr.lgappstv.com";
				// } else if (port == "8006") {
					// billingUrl = "qt2-kr.lgappstv.com";
				// }
			//}
			return billingUrl;
		},
		checkBilling: function () {
			try{
				var self = this;
				var args = arguments;
				if (CJ.plugin.membership.isLogin()) {
					//$("#testValue").html("checkBilling args length : " + args.length);
					
					if ((args.length > 4) && (args[4] == "19")) {
						CJ.plugin.membership.confirmUser(
								function (userId) {
									if (_BILLING_CHECK_TYPE == 'cp') {
										this.checkPurchase.apply(this, args);
									} else {
										this.checkPaid.apply(this, args);
									}
								},
								function () {
									//CJ.Scene.alert("성인 인증에 실패하였습니다.");
								}
						);
					} else {
						if (_BILLING_CHECK_TYPE == 'cp') {
							this.checkPurchase.apply(this, args);
						} else {
							this.checkPaid.apply(this, args);
						}
					}
					
					//if (!CJ.IS_TV || window.location.port == '9999') {
					//	validCB();
					//	return;
					//} else {
					/*
						if (_BILLING_CHECK_TYPE == 'cp') {
							this.checkPurchase.apply(this, args);
						} else {
							this.checkPaid.apply(this, args);
						}
					*/	
					//}
				} else {
					CJ.plugin.membership.login(
						function () {
							console.log('login after billing call');
							self.checkBilling.apply(self, args);
						},
						function() {
							console.log('login fail');
						});
				}
			} catch  (err) {
				console.log(err.message);
				if (!CJ.IS_TV) {
					return args[3]();
				}
			}
		},
		checkPaid : function (pid, eid, validCB, invalidCB) {
			this.DeviceAPI.onCheckPaid = function (event) {
				if (event.result) {
					validCB();
				} else {
					invalidCB();
				}
			};
			this.DeviceAPI.checkPaid(this.getProductIDs(pid, eid), 1);
		},
		getPrice : function (pid, eid, succCB, errorCB) {
			CJ.HttpJson.get({
				type: 'CONTENTSINFO',
				param: {
					"ProgramID": pid,
					"EpisodeID": eid
				},
				success: function (json) {
					succCB(json);
				},
				error: function (jqXHR) {
					if (typeof errorCB == 'function') {
						errorCB(jqXHR);
					}
				}
			});
		},
		checkPurchase : function (pid, eid, validCB, invalidCB) {
			CJ.HttpJson.get({
				type: 'CONTENSPAYMENT',
				param: {
					"userID": this.getUserID(),
					"ProgramID": pid,
					"EpisodeID": eid
				},
				success: function (json) {
					if (json.resultcode == "100") {
						validCB();
					} else {
						invalidCB();
					}
				},
				error: function (jqXHR) {
					console.log('과금 확인 에러');
					invalidCB();
				}
			});
		},
		purchase : function (eType, price, pid, eid, succCB, errorCB) {
			try{
				var prdtID, prdtName, realPurAmt, etc;
				var chargeType;
				var chargePrdUnit;
				var chargePrdVal;
				var chargeCntVal;
				var cjBillingType;

				if (eType == 'single') {
					prdtID = _BILLING_SINGLE_.replace('{{programID}}', pid).replace('{{episodenumber}}', eid);
					chargeType = 2; //2: fixed rate (term)
					chargePrdUnit = 3; //0: N/A, 1: year, 2: month, 3: day, 4: hour, 5: minute
					chargePrdVal = 7; //7day
					chargeCntVal = 0;
					cjBillingType = 0;
				} else if (eType == 'series') {
					prdtID = _BILLING_SERIES.replace('{{programID}}', pid);
					chargeType = 2;  //2: fixed rate (term)
					chargePrdUnit = 3; //0: N/A, 1: year, 2: month, 3: day, 4: hour, 5: minute
					chargePrdVal = 7; //7day
					chargeCntVal = 0;
					cjBillingType = 1;
				} else {
					prdtID = _BILLING_MONTH;
					chargeType = 2;  //2: fixed rate (term)
					chargePrdUnit = 2; //0: N/A, 1: year, 2: month, 3: day, 4: hour, 5: minute
					chargePrdVal = 1; // 1 month
					chargeCntVal = 0;
					cjBillingType = 1;
				}

				prdtName = _PRODUCT_NAME[eType];
				realPurAmt = price;

				this.DeviceAPI.onPurchase = function (event) {
					if (event.result) {
						console.log("purchased");
						//CP server에서 Billing 정보 기록
						CJ.HttpJson.get({
							type: 'BUY',
							param: {
								"userID": this.getUserID(),
								"buyType": cjBillingType, //(0:단편구매,1:월정액,2:시리즈구매)
								"ProgramID": pid,
								"EpisodeID": eid,
								"chargeNo": event.chargeNo,
								"responseEncData": event.responseEncData
							},
							success:  function (json) {
								if (json.resultcode == '100') {
									succCB();
								} else {
									errorCB();
								}
							},
							error: function () {
								console.log('과금 체크 결과 ' + json.resultcode);
								errorCB();
							}
						});
					} else {
						console.log("not purchased");
						errorCB();
					}
				};

				_REQENCDATA = prdtID+realPurAmt+chargeType+chargePrdUnit+chargePrdVal+chargeCntVal+_STRAPPID;
				
				/* 상용 결제 */
				var etc = 'sellrFlag=2&purCount=' + _PURCOUNT
									+ '&prdtBasAmt=' + realPurAmt + '&cntryCode=' + _CNTRYCODE
									+ '&prdtTpName=unit&prdtCat=&prdtCatName=&prdtSubCatName='
									+ '&chargeType=' + chargeType
									+ '&chargePrdUnit=' + chargePrdUnit
									+ '&chargePrdVal=' + chargePrdVal
									+ '&chargeCntVal=' + chargeCntVal
									+ '&reqOrdID=&reqEncData=' + _REQENCDATA;
				if (CJ.plugin.device.getPlatform()  == 'NetCast 4.0' && eType == 'term') {
					etc = etc + "&recurrFlag=Y&recurrPrdUnit=" + _CHARGEPRDUNIT + "&recurrPrdVal=" + _CHARGEPRDVAL;
				}
				/** 1일 단위로 결제 테스트용 코드
				var etc = 'sellrFlag=2&purCount=' + _PURCOUNT
									+ '&prdtBasAmt=' + realPurAmt + '&cntryCode=' + _CNTRYCODE
									+ '&prdtTpName=unit&prdtCat=&prdtCatName=&prdtSubCatName'
									+ '&chargeType=' + 2
									+ '&chargePrdUnit=' + 3
									+ '&chargePrdVal=' + 1
									+ '&chargeCntVal=' + 0
									+ '&reqOrdID=&reqEncData=' + _REQENCDATA;
				**/

				console.log(prdtID + " , " + prdtName + " , " + realPurAmt + " , " + _CURRCODE + " , " + etc);
				//this.DeviceAPI.billing_purchase(prdtID, prdtName, realPurAmt, _CURRCODE, etc);
				succCB();
			} catch  (err) {
				console.log(err.message);
				if (!CJ.IS_TV) {
					return succCB();
				}
			}
		}
	};


	$(document).ready(function(){
		CJ.plugin.billing.init();
	});
})();